import Vuex from 'vuex'
import { miniLogin, getUserInfo } from '@/api/index'
import type { Login_params } from '@/api/index.type'
import { queryImAccout } from '@/api/im'

const modulesFiles = import.meta.glob('./modules/*.ts', { eager: true })
const modules = Object.keys(modulesFiles).reduce((p, n) => {
  const moduleName = n.replace(/^\.\/modules\/(.+)\.ts$/, '$1')
  const value = modulesFiles[n]
  p[moduleName] = value.default
  return p
}, {})

interface state {
  token: string
  userInfo: object
  appId: string
  windowInfo: object
  system: string
}

const getters = {}
const state: state = {
  token: uni.getStorageSync('token') || '',
  userInfo: {},
  appId: 'wxc24c1886d22cd193',
  windowInfo: {},
  system: ''
}

const mutations = {
  setToken(state, payload: string) {
    state.token = payload
    if (state.token) {
      uni.setStorageSync('token', payload)
    } else {
      uni.removeStorageSync('token')
    }
  },
  setAppid(state, payload: string) {
    state.appId = payload
  },
  SET_USERINFO(state, payload: object) {
    state.userInfo = payload
    console.log(payload)
    if (String(payload) !== '{}') {
      uni.setStorageSync('userInfo', JSON.stringify(payload))
    } else {
      uni.removeStorageSync('userInfo')
    }
  },
  setWindowInfo(state, payload) {
    state.windowInfo = payload
  },
  setSystem(state, payload) {
    state.system = payload
  }
}

const actions = {
  getToken({ commit, state }) {
    return new Promise((resolve, reject) => {
      // #ifdef MP-WEIXIN || MP-ALIPAY
      const appid = wx.getAccountInfoSync().miniProgram.appId
      console.log(appid)

      commit('setAppid', appid)

      uni.login({
        success: (res) => {
          const params: Login_params = {
            appId: appid,
            code: res.code,
            loginId: '',
            loginSource: 3,
            loginType: 3,
            platform: 'wechat',
            userType: 1,
            verifyCode: '',
            verifyKey: ''
          }
          miniLogin(params)
            .then((res) => {
              if (res.code === 0) {
                commit('setToken', res.data.token)
                resolve(res.data)
              } else {
                reject({
                  code: 500,
                  msg: '获取token接口异常'
                })
              }
            })
            .catch((e) => {
              reject(e)
            })
        }
      })
      // #endif
      // #ifdef WEB
      uni.reLaunch({
        url: '/pages/login/index'
      })
      reject()
      // #endif
    })
  },
  getUserInfoByToken({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then((res) => {
          if (res.code === 0) {
            resolve(res.data)
            console.log('客户用户信息', res.data)
          } else {
            reject({
              code: 500,
              msg: '获取用户信息接口异常'
            })
          }
        })
        .catch((e) => {
          reject(e)
        })
    })
  },
  async setUserInfo({ commit, rootState, dispatch }, payload) {
    try {
      if (!rootState.token) {
        await dispatch('getToken')
      }
      // 未注册
      const info = await dispatch('getUserInfoByToken')
      if (info.userStatus === 0) {
        uni.reLaunch({
          url: '/pages/login/index'
        })
      } else {
        commit('SET_USERINFO', info)
        const { data } = await queryImAccout()
        dispatch('im/IM_CONNECT', {
          accid: data.accountId,
          token: data.token,
          appId: '85a4d5b702808cb1cd9809be4e1e5847'
        })
        // dispatch('im/IM_CONNECT', {
        //   accid: 'd45e5755c6d1227b83fc68dcc35192a4',
        //   token: '2066f95e29dc4154ba722e66bdf7464a',
        //   appId: '85a4d5b702808cb1cd9809be4e1e5847'
        // })

        if (payload && payload.success) {
          payload.success()
        } else {
          uni.reLaunch({
            url: '/pages/userPage/customerService'
          })
        }
      }
    } catch (e) {
      if (e.code && e.code === 401) {
        // token师表已有提示不重复提示
      } else if (payload && payload.fail) {
        payload.fail()
      } else {
        uni.showModal({
          title: '提示',
          content: '网络异常，点击确定重新登录',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              dispatch('setUserInfo')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
  }
}

const store = new Vuex.Store({
  getters,
  state,
  mutations,
  actions,
  modules
})

export default store
